package xin.yangshuai.juc01.hello;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Question2
 *
 * @author shuai
 * @date 2022/2/11
 */
public class Question2 {

    private int num;

    private Lock lock = new ReentrantLock();

    public Question2() {
    }

    public Question2(int num) {
        this.num = num;
    }

    public void sale() {
        lock.lock();
        try {

            if (num > 0) {
                System.out.println("LOCK，有 " + (num--) + " 张票，" + Thread.currentThread().getName() + "卖出 1 张，还剩 " + num + " 张");
            }

        } finally {
            lock.unlock();
        }
    }

    public synchronized void sale1() {

        if (num > 0) {
            System.out.println("synchronized，有 " + (num--) + " 张票，" + Thread.currentThread().getName() + "卖出 1 张，还剩 " + num + " 张");
        }


    }
}

class Result1 {
    public static void main(String[] args) {
        Question2 question2 = new Question2(30);

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 30; i++) {
                    question2.sale();
                }
            }
        }, "AA").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 30; i++) {
                    question2.sale();
                }
            }
        }, "BB").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 30; i++) {
                    question2.sale();
                }
            }
        }, "CC").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 30; i++) {
                    question2.sale();
                }
            }
        }, "DD").start();
    }
}
